#include "statussetreq.h"

StatusSetReq::StatusSetReq(bool status) : SimpleProtoSrv(PT_STATUS_SET)
{
    addString(status ? "1" : "0");
}

ProtoSrv* StatusSetReq::decode(ACE_InputCDR &cdr)
{
    SimpleProtoSrv* request = new StatusSetReq();
    if(!SimpleProtoSrv::decode(cdr,request)){
        delete request;
        request = 0;
    }

    return request;
}

ProtoSrv* StatusSetReq::execute(ACE_SOCK_Stream &peer)
{
    SimpleProtoSrv *resp = 0;

    long status;
    if(this->getLong(status,0)){
        resp = new SimpleProtoSrv(PT_RESP_STATUS_SET);

        int result = E_FAIL;
        Client client(peer.get_handle());
        Room *room = RoomManager::getInstance()->getRoomByClient(client);
        if(room && room->setClientReady(client,(bool)status))
            result = E_SUCCESS;

        resp->addLong(result);

        if(status && result == E_SUCCESS && room->isReady()){   //room is ready for starting game
            std::auto_ptr<SimpleProtoSrv> notify(new SimpleProtoSrv(PT_NOTIFY_GAME_START));
            notify->addString(room->getName());
            TetrixServer::getInstance()->broadcast(notify);
        }
    }

    return resp;
}
